package com.nkbh.sevenday.camera.camera1.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.nkbh.sevenday.camera.R;
import com.nkbh.sevenday.camera.utils.CommonUtil;
import com.nkbh.sevenday.camera.utils.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 获取摄像头中的返回的实时数据，并对其进行相应的处理
 */
public class CameraRealTimeDataActivity extends AppCompatActivity {

    private static final String TAG = "CameraRealTimeDataActivity";
    SurfaceView mSfv;

    Camera mCamera;

    SurfaceHolder mHolder;
    Bitmap bitmap;
    ImageView img;

    int n=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_real_time_data);
        initView();
        creatCamera(1);
    }

    @SuppressLint("LongLogTag")
    private void creatCamera(int openId) {
        if (!CommonUtil.checkCameraHardware(this)){
            ToastUtil.showMessage(this,"没有硬件设备");
        }

        mCamera=Camera.open(openId);

        mHolder = mSfv.getHolder();

        mHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    mCamera.setPreviewDisplay(holder);
                    mCamera.setDisplayOrientation(90);
                    mCamera.startPreview();
                    startFaceDetection();//开启人脸识别
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                mCamera.stopPreview();
                try {
                    mCamera.setPreviewDisplay(holder);
                    mCamera.setDisplayOrientation(90);
                    mCamera.startPreview();
                    startFaceDetection();//开启人脸识别
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mCamera!=null){
                    mCamera.stopPreview();
                    mCamera.release();
                }
            }
        });


//        Camera.Parameters parameters = mCamera.getParameters();
//
//        parameters.setPreviewSize(480,480);
//        parameters.setPictureSize(480,480);
//        parameters.setPreviewFormat(ImageFormat.NV21);
//
//        List<Integer> list=parameters.getSupportedPreviewFormats();
//        for (Integer val :list) {
//            Log.i(TAG, "creatCamera: val="+val);
//        }
//
//        List<Camera.Size> sizeList=parameters.getSupportedPreviewSizes();
//
//        if (sizeList.size()>1){
//            Iterator<Camera.Size> iterator=sizeList.iterator();
//            while (iterator.hasNext()){
//                Camera.Size size = iterator.next();
//                Log.i(TAG, "creatCamera: w="+size.width+"  h="+size.height);
//            }
//        }
//
//
//        mCamera.setParameters(parameters);

        setParameter();

        mCamera.setPreviewCallback(new Camera.PreviewCallback() {
            @SuppressLint("LongLogTag")
            @Override
            public void onPreviewFrame(final byte[] data, final Camera camera) {
                if (n>20){
                    Log.i(TAG, "onPreviewFrame: data===="+data);
                    if (bitmap==null) {
                        bitmap=byte2bitmap(data, camera);
                        img.setImageBitmap(bitmap);
                    }
                }
                n++;
            }
        });

        mCamera.setFaceDetectionListener(new Camera.FaceDetectionListener() {
            @Override
            public void onFaceDetection(Camera.Face[] faces, Camera camera) {
                if (faces.length>0){
                    Log.d("FaceDetection", "face detected: "+ faces.length +
                            " Face 1 Location X: " + faces[0].rect.centerX() +
                            "Y: " + faces[0].rect.centerY() );
                }
            }
        });

    }

    /**
     * 设置照片格式
     *
     */
    private void setParameter() {
        Camera.Parameters parameters = mCamera.getParameters(); // 获取各项参数
        parameters.setPictureFormat(PixelFormat.JPEG); // 设置图片格式
        parameters.setJpegQuality(100); // 设置照片质量
        //获得相机支持的照片尺寸,选择合适的尺寸
        List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;
        int maxSize = Math.max(width, height);
        int length = sizes.size();
        if (maxSize > 0) {
            for (int i = 0; i < length; i++) {
                if (maxSize <= Math.max(sizes.get(i).width, sizes.get(i).height)) {
                    parameters.setPictureSize(sizes.get(i).width, sizes.get(i).height);
                    break;
                }
            }
        }
        List<Camera.Size> ShowSizes = parameters.getSupportedPreviewSizes();
        int showLength = ShowSizes.size();
        if (maxSize > 0) {
            for (int i = 0; i < showLength; i++) {
                if (maxSize <= Math.max(ShowSizes.get(i).width, ShowSizes.get(i).height)) {
                    parameters.setPreviewSize(ShowSizes.get(i).width, ShowSizes.get(i).height);
                    break;
                }
            }
        }
        parameters.setPreviewFormat(ImageFormat.NV21);
        mCamera.setParameters(parameters);
    }

    public void startFaceDetection(){
        // Try starting Face Detection
        Camera.Parameters params = mCamera.getParameters();

        // start face detection only *after* preview has started
        if (params.getMaxNumDetectedFaces() > 0){
            // camera supports face detection, so can start it:
            mCamera.startFaceDetection();
        }
    }

    private Bitmap byte2bitmap(byte[] bytes, Camera camera) {
        Bitmap bitmap = null;

        Camera.Size size = camera.getParameters().getPreviewSize(); // 获取预览大小
        final int w = size.width; // 宽度
        final int h = size.height;
        final YuvImage image = new YuvImage(bytes, ImageFormat.NV21, w, h,
                null);
        ByteArrayOutputStream os = new ByteArrayOutputStream(bytes.length);
        if (!image.compressToJpeg(new Rect(0, 0, w, h), 100, os)) {
            return null;
        }
        byte[] tmp = os.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);

        Matrix matrix = new Matrix();
        matrix.setRotate(-90);
        bitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);

        return bitmap;
    }

    private void initView() {
        mSfv=findViewById(R.id.sfv);
        img=findViewById(R.id.img);
    }

}
